/* eslint-disable max-len */
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Upload, Table, Input } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, DATETIME_TEXT } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import styles from './Notice.module.scss';
import moment from 'moment';

const FromItem = Form.Item;

const NoticeForm = ({ noticeInfo, modal, onCancel, onSubmit, handleCustomRequest }) => {
  const { noticeStore: store } = useStore();
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [notice] = useState(() => observable({}));
  const [idx, setIdx] = useState();
  const [state, setState] = useState([]);

  const uploaderRef = useRef();
  const [disabledAdd, setDisabledAdd] = useState(false);

  useEffect(() => { if (modal?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    (async () => {
      await store.getActivitys();
      if (JSON.stringify(noticeInfo) !== '{}') {
        const res = await store.get(noticeInfo?.id);
        const { imgConfigs, beginTime, endTime, extra } = res;
        _.assign(notice, res);
        editCtx.origin = _.cloneDeep(res);
        if (extra && JSON.stringify(extra) !== '{}') {
          const toggleExtra = Object.entries(extra).map(([itemId, content]) => ({ itemId, content }));
          for (const key in extra) {
            if (Object.hasOwnProperty.call(extra, key)) {
              const element = extra[key];
              if (key === 'activityId') {
                _.set(notice, 'activityId', element);
              }
            }
          }
          setState(toggleExtra);
        }
        if (JSON.stringify(imgConfigs) !== '[]') {
          setDisabledAdd(true);
        }
        if (beginTime || endTime) {
          const begin = DATETIME_TEXT(beginTime);
          const end = DATETIME_TEXT(endTime);
          _.set(notice, 'timeScope', [begin, end]);
        } else {
          _.set(notice, 'timeScope', []);
        }
      } else {
        _.assign(notice, {});
        _.set(notice, 'imgConfigs', []);
        _.set(notice, 'extra', {});
        _.set(notice, 'timeScope', []);
        _.set(notice, 'showPalace', []);
        _.set(notice, 'enable', true);
        _.set(notice, 'type', '');
        _.set(notice, 'triggerMethod', '');
        _.set(notice, 'interactionMode', '');
        _.set(notice, 'sortWeight', 1);
        editCtx.origin = _.cloneDeep({});
      }
    })();
  }, []);

  const overrideModel = {
    imgConfigs: {
      label: t`图片`,
      ui: {
        renderer: (r) => {
          const img = r?.map((item) => {
            if (item.originFileObj) {
              return item;
            }
            return ({
              uid: item.uid,
              state: 'done',
              name: item.name,
              type: item.type,
              url: `${API_BASE}/api/files/${item.uid}`,
              downloadURL: `${API_BASE}/api/files/${item.uid}`,
              imgURL: `${API_BASE}/api/files/${item.uid}`,
            });
          });
          return (
            <Upload.Card
              listType="card"
              className={disabledAdd ? styles.disabled_add : styles.container}
              value={img}
              name="imgConfigs"
              beforeUpload={beforeUpload}
              headers={{ Authorization: `Bearer ${TOKEN}` }}
              data={(file) => {
                return { binaryId: file.uid, mimeType: file.type };
              }}
              autoUpload={false}
              ref={saveUploaderRef}
              onPreview={handlePreview}
              formatter={(res, files) => {
                return {
                  uid: files.uid,
                  name: files.name,
                  state: 'done',
                  type: files.type,
                  url: `${API_BASE}/api/files/${files.uid}`,
                  downloadURL: `${API_BASE}/api/files/${files.uid}`,
                  imgURL: `${API_BASE}/api/files/${files.uid}`,
                };
              }}
              request={customRequest}
              onChange={handleUploadAdd}
              useDataURL
              action={`${API_BASE}/upload`}
              accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp, image/webp"
            />
          );
        },
      },
    },
    extras: {
      ui: {
        renderer: (__) => (
          <>
            {!isViewMode && <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddState()}>{t`添加属性`}</Button>}
            <Table
              hasBorder={false}
              dataSource={state}
              columns={[
                {
                  title: t`序号`,
                  dataIndex: 'id',
                  align: 'center',
                  cell: (v, i) => <span>{i + 1}</span>,
                },
                {
                  title: t`标识`,
                  dataIndex: 'itemId',
                  width: 300,
                  align: 'center',
                  cell: (v) => <Input onChange={handelChangeName} style={{ width: '100%' }} value={v} />,
                },
                {
                  title: t`内容`,
                  dataIndex: 'content',
                  width: 400,
                  align: 'center',
                  cell: (v) => <Input onChange={handleChangeContent} style={{ width: '100%' }} value={v} />,
                },
                {
                  title: t`操作`,
                  dataIndex: 'name',
                  align: 'center',
                  cell: (v, i) => (
                    <>
                      <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i)}>{t`删除`}</Button>
                    </>
                  ),
                },
              ]}
              onRowClick={(_, index) => setIdx(index)}
            />
          </>
        ),
        span: 4,
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(notice, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const saveUploaderRef = (ref) => {
    if (ref) uploaderRef.current = ref.getInstance();
  };

  const beforeUpload = (info, options) => {
    return options;
  };

  const customRequest = (data) => {
    handleCustomRequest(data);
  };

  /**
  * @description 上传组件事件
  * @param {*} v
  */
  const handleUploadAdd = (v) => {
    if (v?.length >= 1) {
      _.set(notice, 'imgConfigs', v);
      setDisabledAdd(true);
    } else {
      setDisabledAdd(false);
    }
  };

  const handlePreview = ({ url }) => {
    Dialog.show({
      title: t`预览`,
      content: <img src={url} style={{ maxWidth: '800px', width: '100%', height: '100%', objectFit: 'cover' }} />,
      footer: false,
    });
  };

  const handleAddState = () => {
    const data = {
      itemId: '',
      content: '',
    };
    setState((pre) => {
      const cloneData = [...pre];
      cloneData.push(data);
      return cloneData;
    });
  };

  const handelChangeName = (v) => {
    setState((pre) => {
      const toggle = [...pre];
      toggle[idx].itemId = v;
      return toggle;
    });
  };

  const handleChangeContent = (v) => {
    setState((pre) => {
      const toggle = [...pre];
      toggle[idx].content = v;
      return toggle;
    });
  };

  const handleDeleteState = (i) => {
    setState((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  /**
   * @description 提交表单实现修改配置
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const { imgConfigs, timeScope, type, activityId } = notice;
    let toggleImg = [];
    if (JSON.stringify(imgConfigs) !== '[]') {
      toggleImg = imgConfigs.map((item) => ({
        name: item.name,
        uid: item.uid,
        type: item.type,
      }));
    }
    const tempState = _.cloneDeep(state);
    if (JSON.stringify(timeScope) !== '[]') {
      const toggleTime = timeScope.map((item) => moment(item).utc().format());
      _.set(notice, 'beginTime', toggleTime[0]);
      _.set(notice, 'endTime', toggleTime[1]);
    } else {
      _.set(notice, 'beginTime', null);
      _.set(notice, 'endTime', null);
    }
    if (type === '2' && activityId) {
      if (tempState?.length === 0) {
        tempState.push({ itemId: 'activityId', content: activityId });
      } else {
        for (let i = 0; i < tempState.length; i++) {
          const element = state[i];
          if (element.itemId === 'activityId') {
            element.content = activityId;
          }
          break;
        }
      }
    }
    const toggleState = tempState?.reduce((acc, item) => {
      const { itemId, content } = item;
      acc[itemId] = content;
      return acc;
    }, {});
    _.set(notice, 'extra', toggleState);
    _.unset(notice, 'timeScope');
    _.set(notice, 'imgConfigs', toggleImg);
    onSubmit?.(notice);
    uploaderRef.current && uploaderRef.current.startUpload();
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={notice}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`公告信息`} />
      <FieldsGrid
        formData={notice}
        mode={modal}
        columns={4}
        overrideModel={overrideModel}
        fields={[
          'name',
          'mainTitle',
          'subTitle',
          'showPalace',
          'type',
          'triggerMethod',
        ].concat(notice.type === '2' ? ['interactionMode', 'activityId'] : []).concat([
          'enable',
          'timeScope',
          'link',
          'sortWeight',
        ])}
      />
      <FieldsGrid
        formData={notice}
        mode={modal}
        columns={4}
        overrideModel={overrideModel}
        fields={[
          'content',
        ]}
      />
      <TitleGrid title={t`图片信息`} />
      <FieldsGrid
        formData={notice}
        mode={modal}
        columns={4}
        overrideModel={overrideModel}
        fields={[
          'imgConfigs',
        ]}
      />
      <TitleGrid title={t`其他信息`} />
      <FieldsGrid
        formData={notice}
        mode={modal}
        columns={4}
        overrideModel={overrideModel}
        fields={[
          'extras',
        ]}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(NoticeForm);
